package com.ctg.itrdc.imageconsole.service.scheduler;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.data.entity.DockerMicroAppRefer;
import com.ctg.itrdc.imageconsole.service.IDockerMicroAppReferService;
import com.ctg.itrdc.imageconsole.service.IServiceDependService;

/**
 * 定时任务，rc自动伸缩
 * @author wupiao
 *
 */
@Component("serviceDependScheduler")
public class ServiceDependScheduler implements IScheduler, Runnable {

	private static final Logger logger = LoggerFactory.getLogger(ServiceDependScheduler.class);

	private int totalThreadCount = Runtime.getRuntime().availableProcessors() * 2;

	private ExecutorService executorService = Executors.newFixedThreadPool(totalThreadCount);

	@Resource
	private IDockerMicroAppReferService dockerMicroAppReferService;
	@Resource
	private IServiceDependService serviceDependService;

	/**
	 * 获取线程池空闲线程数
	 * 
	 * @return
	 */
	private int getIdleThreadCount() {
		int activeThreadCountInPool = ((ThreadPoolExecutor) executorService).getActiveCount();
		return totalThreadCount - activeThreadCountInPool;
	}

	@Override
	public void run() {
		int idleThreadCount = getIdleThreadCount();
		logger.debug("Thread pool idle thread count [{}]", idleThreadCount);
		if (idleThreadCount <= 0) {
			return;
		}
		List<DockerMicroAppRefer> appRefers = dockerMicroAppReferService.findMicroAppRefers(new DockerMicroAppRefer());
		for (final DockerMicroAppRefer appRefer : appRefers) {
			executorService.submit(new Runnable() {
				@Override
				public void run() {
//					serviceDependService.checkDependence(appRefer);
				}
			});
		}
	}

	public int getTotalThreadCount() {
		return totalThreadCount;
	}

	public void setTotalThreadCount(int totalThreadCount) {
		this.totalThreadCount = totalThreadCount;
	}

}
